package com.suray.rgv.son.comm;

import com.suray.rgv.son.data.ModbusReadMessage;
import com.suray.rgv.son.data.RgvReadRecMessage;

import java.io.IOException;

/**
 * 子车读取数据
 */
public class RgvSonReadData {

    private ModbusReadMessage readMessage;
    private RgvReadRecMessage rgvReadRecMessage;
    private RgvSonComm rgvSonComm;

    public RgvSonReadData(RgvSonComm rgvSonComm) {
        this.rgvSonComm = rgvSonComm;
        readMessage = new ModbusReadMessage();
        rgvReadRecMessage = new RgvReadRecMessage();
    }

    /**
     * 读取子车状态
     * @param startAddress
     * @param readSize
     * @return
     * @throws IOException
     */
    public RgvReadRecMessage readData(int startAddress, int readSize) throws IOException {
        readMessage.setMessageInfo(startAddress, readSize);
        byte[] recData = rgvSonComm.comm("", readMessage, 5);
        rgvReadRecMessage.readMessage(recData);
        validateRecMessage(rgvReadRecMessage, readMessage, recData);
        return rgvReadRecMessage;
    }

    /**
     * 校验返回数据
     * @param writeRecMessage
     * @param writeMessage
     * @param recData
     */
    private void validateRecMessage(RgvReadRecMessage writeRecMessage, ModbusReadMessage writeMessage, byte[] recData) {
        writeRecMessage.validateMessage(writeMessage.getSlaveAddr(), writeMessage.getStartAddr(),
                writeRecMessage.calcCrc(recData));
    }
}
